package com.android.sharecar.activity;

import com.android.sharecar.activity.config.SignupStep1Activity;
import com.android.sharecar.service.ShareCarBGService;
import com.android.sharecar.util.ConfigUtil;
import com.android.sharecar.util.SysUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.IOException;

/**
 * LoginActivity. 
 * Deal the login transactions.
 * 
 * @version 0.2 
 * @author xinyan
 * @date 2011-9-7
 */
public class LoginActivity extends Activity {

	private EditText mAccount; // var for account
	private EditText mPassword; // var for password
	private Button mLogin; // var for login button
	private CheckBox mRememberPwd; // var for save password checkbox
	private ImageView mHeadPicture; // var for head picture
	private Button mSignup; // var for signup button

	private static ConfigUtil util;
	private static Context mContext;

	public static final String TAG = "LoginActivity";

	// login result constants
	public static final int LOGIN_RESULT_SUCCESS = 1; // login success
	public static final int LOGIN_RESULT_NOT_EXIST = 0; // account not exist

	// login result: account or password error
	public static final int LOGIN_RESULT_ERROR = -1;

	// creat an alert dialog for account not exist, and the following var
	// is named at the same way
	public static final String ALERT_TYPE_NOT_EXIST = "not_exist"; //
	public static final String ALERT_TYPE_ERROR = "error";
	public static final String ALERT_TYPE_IOEXCEPTION = "ioexception";
	public static final String ALERT_TYPE_AC_PWD_EMPTY = "empty";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);

		findViews();
		setListenerForViews();

		util = new ConfigUtil(this);
		// initialLogin();

	}

	private void setListenerForViews() {
		mSignup.setOnClickListener(new View.OnClickListener() {

			// Forward to the signup activity after user clicked the signup
			// button
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(LoginActivity.this,
						SignupStep1Activity.class);

				Log.v(TAG,
						"signup button was clicked, and prepare to start signup activity.");
				startActivity(intent);
				Log.v(TAG, "startActivity method executed.");
			}
		});

		// set the login button listener
		mLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String strAccount = mAccount.getText().toString();
				String strPWD = mPassword.getText().toString();

				try {

					// start background service here.
					ComponentName cnServiceReturn = LoginActivity.this
							.startService(new Intent(LoginActivity.this,
									ShareCarBGService.class));
					if (cnServiceReturn.getClassName() != null) {
						Log.v(TAG, "service start successfully, its name is "
								+ cnServiceReturn.getClassName());
					} else {
						Log.v(TAG, "service start failed.");
					}

					// go into main activity directly
					Intent intent = new Intent();
					intent.setClass(LoginActivity.this,
							MainTabWidgetActivity.class);
					startActivity(intent);
				} catch (Exception e) {
					Log.e(TAG,
							"start service ShareCarBGService occurs exception, msg: "
									+ e.getMessage());
				}
				return;
				/*if (!strAccount.equals("") && !strPWD.equals("")) {
					try {
						Log.v(TAG, "Start to login. account is :" + strAccount
								+ " | password is : " + strPWD);

						int result = login(strAccount, strPWD);

						Log.v(TAG, "received login result, the value is:"
								+ result);

						// we set the login result as true for debug and test
						// other functions quickly.

						result = LOGIN_RESULT_SUCCESS;

						switch (result) {
						case LOGIN_RESULT_SUCCESS:
							// we should save the password before we go
							if (mRememberPwd.isChecked()) {
								util.saveString("account", strAccount);
								util.saveString("password", strPWD);
							}
							// go into main activity directly
							Intent intent = new Intent();
							intent.setClass(LoginActivity.this,
									MainTabWidgetActivity.class);
							intent.putExtra(StandardActivity.STATE, StandardActivity.STATE_NORMAL);
							startActivity(intent);

							break;
						case LOGIN_RESULT_NOT_EXIST:

							Log.v(TAG,
									"Account is not exist, going to show an alertdialog");

							AlertDialog alert_Not_Exist = creatBuilder(
									ALERT_TYPE_NOT_EXIST).create();
							alert_Not_Exist.show();
							break;
						case LOGIN_RESULT_ERROR:

							Log.v(TAG,
									"Account or password error, going to show an alertdialog ");

							AlertDialog alert_Error = creatBuilder(
									ALERT_TYPE_ERROR).create();
							alert_Error.show();
							break;

						default:
							break;
						}
					} catch (IOException e) {
						Log.e(TAG, "Catch an exception, exception message is:"
								+ e.getMessage());

						AlertDialog alert_IOException = creatBuilder(
								ALERT_TYPE_IOEXCEPTION).create();
						alert_IOException.show();
						return;
					}
				} else { // else the value of account or password is empty
					Log.v(TAG, "Account or password empty.");

					AlertDialog alert_Empty = creatBuilder(
							ALERT_TYPE_AC_PWD_EMPTY).create();
					alert_Empty.show();
				}*/
			}

		});
	}

	private void findViews() {
		mAccount = (EditText) findViewById(R.id.login_et_account);
		mPassword = (EditText) findViewById(R.id.login_et_pwd);
		mLogin = (Button) findViewById(R.id.login_btn_login);
		mRememberPwd = (CheckBox) findViewById(R.id.login_cb_savepwd);
		mSignup = (Button) findViewById(R.id.login_btn_signup);

	}

	/**
	 * initialize the saved account and password and head picture
	 */
	private void initialLogin() {
		String strAccount = "";
		String strPassword = "";
		// how to define an image object???

		strAccount = util.getString("account");
		strPassword = util.getString("password");

	}

	/**
	 * This is a method for checking user's account and password
	 * 
	 * @param account
	 *            account is an e-mail
	 * @param password
	 *            password
	 * @return integers stands for login result
	 * @throws IOException
	 */
	private int login(String account, String password) throws IOException {
		if (account.equals("test@t.t") && password.equals("test")) {
			return LOGIN_RESULT_SUCCESS;
		} else {
			return LOGIN_RESULT_NOT_EXIST;
		}

	}

	/**
	 * Builder creator, used for create all kinds of warning dialog in this
	 * activity
	 * 
	 * @param type
	 *            alert type, constants listed on the top area.
	 * @return return a builder
	 */
	private AlertDialog.Builder creatBuilder(String type) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				LoginActivity.this);
		builder.setTitle("警告");
		if (ALERT_TYPE_NOT_EXIST == type) {
			builder.setMessage("您输入的账号不存在！请注册");
		} else if (ALERT_TYPE_ERROR == type) {
			builder.setMessage("您输入的账号或密码错误！请重新输入");
		} else if (ALERT_TYPE_IOEXCEPTION == type) {
			builder.setMessage("网络错误！请检查是否已经连接网络");
		} else if (ALERT_TYPE_AC_PWD_EMPTY == type) {
			builder.setMessage("账号或密码为空！请重新输入");
		}
		builder.setPositiveButton("确定", null);

		return builder;
	}

	// 这里用来接受退出程序的指令
	@Override
	protected void onStart() {
		int flag = getIntent().getIntExtra("flag", 0);
		if (flag == SysUtil.EXIT_APPLICATION) {
			finish();
		}
		super.onResume();

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	// 当activity是单例的时候,再次启动该activity就不会再调用 oncreate->onstart这些方法了
	@Override
	protected void onNewIntent(Intent intent) {
		int flag = getIntent().getIntExtra("flag", 0);
		if (flag == SysUtil.EXIT_APPLICATION) {
			finish();
		}
		super.onNewIntent(intent);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
}